package com.tanjun.userservice.web.biz.api;

import com.tanjun.common.constants.DefaultConstant;
import com.tanjun.common.utils.ConvertUntil;
import com.tanjun.userservice.apiservice.response.admindept.admin.DeptResponse;
import com.tanjun.userservice.apiservice.response.adminrole.admin.AdminRoleResponse;
import com.tanjun.userservice.apiservice.response.adminuser.admin.AdminUserBaseResponse;
import com.tanjun.userservice.apiservice.response.adminuser.api.AdminUserResponse;
import com.tanjun.userservice.web.service.role.BaseAdminRoleService;
import com.tanjun.userservice.web.service.role.entity.BaseAdminRoleEntity;
import com.tanjun.userservice.web.service.user.BaseAdminDeptService;
import com.tanjun.userservice.web.service.user.BaseAdminUserService;
import com.tanjun.userservice.web.service.user.entity.BaseAdminDeptEntity;
import com.tanjun.userservice.web.service.user.entity.BaseAdminUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminUserApiBiz {
    @Autowired
    private BaseAdminUserService baseAdminUserService;
    @Autowired
    private BaseAdminDeptService baseAdminDeptService;
    @Autowired
    private BaseAdminRoleService baseAdminRoleService;
    /**
     * 根据用户唯一信息获取用户信息
     *
     * @param key 手机号、登录名、邮箱
     * @return 用户基础信息
     */
    public AdminUserBaseResponse getAdminBaseInfoByKey(String key) {
        BaseAdminUserEntity adminUser= baseAdminUserService.getAdminUserByKey(key);
        return ConvertUntil.convert(adminUser, AdminUserBaseResponse.class);
    }

    /**
     * 根据id获取管理员账户信息
     *
     * @param userId 用户id
     * @return 用户信息
     */
    public AdminUserResponse getByUsrId(Long userId) {
        BaseAdminUserEntity adminUser=baseAdminUserService.getAdminUserByUserId(userId);
        if(adminUser==null){
            return null;
        }
        AdminUserResponse adminUserResponse = ConvertUntil.convert(adminUser, AdminUserResponse.class);
        BaseAdminDeptEntity dept=baseAdminDeptService.getById(adminUserResponse.getDeptId());
        adminUserResponse.setDept(ConvertUntil.convert(dept, DeptResponse.class));

        List<BaseAdminRoleEntity> listRole=baseAdminRoleService.listRolesByIds(adminUserResponse.getRoleIdList());
        adminUserResponse.setRoleNames(listRole.stream().map(BaseAdminRoleEntity::getRoleName)
                .collect(Collectors.joining(DefaultConstant.VIEW_JOIN)));

        adminUserResponse.setRoleIdList(listRole.stream().map(BaseAdminRoleEntity::getRoleId).toList());
        return adminUserResponse;
    }


    /**
     * 根据用户id 返回用户角色
     *
     * @param userId 用户id
     * @return 角色信息
     */
    public List<AdminRoleResponse> listRolesByUserId(Long userId) {
        List<BaseAdminRoleEntity> list=baseAdminRoleService.listRoles(userId);
        return ConvertUntil.convert(list, AdminRoleResponse.class);
    }

}
